<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-4xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">Fullscreen API</h1>
        <p class="text-gray-300 text-lg">
          将元素切换到全屏模式，提供沉浸式的用户体验
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300 mb-4">
          您的浏览器不支持 Fullscreen API。此功能在所有现代浏览器中都有支持。
        </p>
        <p class="text-gray-400 text-sm">
          注意：全屏模式需要用户手势触发（如点击），并且某些浏览器可能使用带前缀的API。
        </p>
      </div>

      <!-- 全屏状态 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">全屏状态</h2>
        
        <div class="bg-gray-800 rounded-lg p-6">
          <div class="flex items-center justify-between mb-6">
            <div class="flex items-center">
              <i :class="isFullscreen ? 'i-carbon-fit-to-screen text-green-400' : 'i-carbon-collapse-all text-gray-400'" class="text-3xl mr-4"></i>
              <div>
                <h3 class="text-lg font-semibold text-white">
                  {{ isFullscreen ? '全屏模式' : '普通模式' }}
                </h3>
                <p class="text-gray-400 text-sm">
                  {{ isFullscreen ? '当前处于全屏状态' : '当前处于窗口模式' }}
                </p>
              </div>
            </div>
            <div :class="isFullscreen ? 'bg-green-600' : 'bg-gray-600'" class="px-4 py-2 rounded-lg">
              <span class="text-white font-semibold">
                {{ isFullscreen ? '已启用' : '未启用' }}
              </span>
            </div>
          </div>

          <div v-if="fullscreenElement" class="mb-4 p-4 bg-gray-900 rounded-lg">
            <p class="text-gray-300 text-sm">
              <strong>全屏元素:</strong> {{ fullscreenElement }}
            </p>
          </div>

          <button
            @click="togglePageFullscreen"
            :disabled="!isSupported"
            class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i :class="isFullscreen ? 'i-carbon-minimize' : 'i-carbon-maximize'" class="mr-2"></i>
            {{ isFullscreen ? '退出全屏' : '进入全屏' }}
          </button>
        </div>
      </div>

      <!-- 全屏演示区域 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">全屏演示</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- 图片全屏 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h3 class="text-lg font-semibold text-white mb-4">图片全屏</h3>
            <div 
              ref="imageContainer"
              class="relative bg-gradient-to-br from-blue-900 to-purple-900 rounded-lg overflow-hidden mb-4 cursor-pointer group"
              @click="toggleImageFullscreen"
            >
              <img
                src="https://images.unsplash.com/photo-1579546929518-9e396f3cc809?w=400"
                alt="示例图片"
                class="w-full h-48 object-cover"
                crossorigin="anonymous"
              >
              <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-40 transition-all duration-300 flex items-center justify-center">
                <i class="i-carbon-maximize text-white text-4xl opacity-0 group-hover:opacity-100 transition-opacity duration-300"></i>
              </div>
            </div>
            <button
              @click="toggleImageFullscreen"
              :disabled="!isSupported"
              class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-4 py-2 rounded-lg transition-colors w-full"
            >
              <i class="i-carbon-image mr-2"></i>
              切换图片全屏
            </button>
          </div>

          <!-- 视频全屏 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h3 class="text-lg font-semibold text-white mb-4">视频全屏</h3>
            <div 
              ref="videoContainer"
              class="relative bg-black rounded-lg overflow-hidden mb-4"
            >
              <video
                ref="videoElement"
                class="w-full h-48 object-cover"
                controls
                src="https://www.w3schools.com/html/mov_bbb.mp4"
              ></video>
            </div>
            <button
              @click="toggleVideoFullscreen"
              :disabled="!isSupported"
              class="bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-4 py-2 rounded-lg transition-colors w-full"
            >
              <i class="i-carbon-video mr-2"></i>
              切换视频全屏
            </button>
          </div>

          <!-- 自定义内容全屏 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h3 class="text-lg font-semibold text-white mb-4">自定义内容</h3>
            <div 
              ref="customContainer"
              class="bg-gradient-to-br from-purple-900 to-pink-900 rounded-lg p-8 mb-4 cursor-pointer"
              @click="toggleCustomFullscreen"
            >
              <div class="text-center text-white">
                <i class="i-carbon-code text-6xl mb-4 block"></i>
                <h4 class="text-2xl font-bold mb-2">自定义内容区域</h4>
                <p class="text-sm opacity-80">点击进入全屏模式</p>
              </div>
            </div>
            <button
              @click="toggleCustomFullscreen"
              :disabled="!isSupported"
              class="bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-4 py-2 rounded-lg transition-colors w-full"
            >
              <i class="i-carbon-crop mr-2"></i>
              切换内容全屏
            </button>
          </div>

          <!-- 文本编辑器全屏 -->
          <div class="bg-gray-800 rounded-lg p-6">
            <h3 class="text-lg font-semibold text-white mb-4">编辑器全屏</h3>
            <div 
              ref="editorContainer"
              class="bg-gray-900 rounded-lg overflow-hidden mb-4"
            >
              <textarea
                v-model="editorContent"
                rows="6"
                class="w-full bg-gray-900 text-white p-4 font-mono text-sm resize-none focus:outline-none"
                placeholder="在这里输入内容..."
              ></textarea>
            </div>
            <button
              @click="toggleEditorFullscreen"
              :disabled="!isSupported"
              class="bg-orange-600 hover:bg-orange-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-4 py-2 rounded-lg transition-colors w-full"
            >
              <i class="i-carbon-text-creation mr-2"></i>
              切换编辑器全屏
            </button>
          </div>
        </div>
      </div>

      <!-- 全屏选项 -->
      <div class="tech-card mb-8">
        <h3 class="text-xl font-semibold mb-6 text-white">全屏选项</h3>
        
        <div class="space-y-4">
          <label class="flex items-center text-gray-300 cursor-pointer">
            <input
              v-model="showFullscreenControls"
              type="checkbox"
              class="mr-3"
            >
            <div>
              <div class="font-medium">显示全屏控制按钮</div>
              <div class="text-sm text-gray-400">在全屏模式下显示退出按钮</div>
            </div>
          </label>

          <label class="flex items-center text-gray-300 cursor-pointer">
            <input
              v-model="preventScroll"
              type="checkbox"
              class="mr-3"
            >
            <div>
              <div class="font-medium">防止滚动</div>
              <div class="text-sm text-gray-400">全屏时禁用页面滚动</div>
            </div>
          </label>

          <label class="flex items-center text-gray-300 cursor-pointer">
            <input
              v-model="autoHideCursor"
              type="checkbox"
              class="mr-3"
            >
            <div>
              <div class="font-medium">自动隐藏光标</div>
              <div class="text-sm text-gray-400">全屏时一段时间后隐藏鼠标光标</div>
            </div>
          </label>
        </div>
      </div>

      <!-- 键盘快捷键 -->
      <div class="tech-card mb-8">
        <h3 class="text-xl font-semibold mb-6 text-white">键盘快捷键</h3>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="bg-gray-800 rounded-lg p-4 flex items-center justify-between">
            <span class="text-gray-300">退出全屏</span>
            <kbd class="px-3 py-1 bg-gray-700 text-white rounded font-mono text-sm">Esc</kbd>
          </div>
          <div class="bg-gray-800 rounded-lg p-4 flex items-center justify-between">
            <span class="text-gray-300">切换全屏 (浏览器默认)</span>
            <kbd class="px-3 py-1 bg-gray-700 text-white rounded font-mono text-sm">F11</kbd>
          </div>
        </div>
      </div>

      <!-- 事件监听 -->
      <div v-if="eventLogs.length > 0" class="tech-card mb-8">
        <h3 class="text-xl font-semibold mb-4 text-white">事件日志</h3>
        
        <div class="space-y-2 max-h-64 overflow-y-auto">
          <div
            v-for="(log, index) in eventLogs.slice().reverse()"
            :key="index"
            class="bg-gray-800 rounded-lg p-3 text-sm"
          >
            <div class="flex justify-between items-center">
              <span class="text-tech-accent font-medium">{{ log.event }}</span>
              <span class="text-gray-400">{{ formatTimestamp(log.timestamp) }}</span>
            </div>
            <p class="text-gray-300 text-xs mt-1">{{ log.details }}</p>
          </div>
        </div>
        
        <div class="mt-4 pt-4 border-t border-gray-700">
          <button
            @click="clearEventLogs"
            class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
          >
            <i class="i-carbon-trash-can mr-1"></i>
            清空日志
          </button>
        </div>
      </div>

      <!-- 错误信息 -->
      <div v-if="error" class="tech-card border-red-600 mb-8">
        <div class="flex items-center mb-2">
          <i class="i-carbon-warning text-red-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-red-500">错误</h3>
        </div>
        <p class="text-gray-300">{{ error }}</p>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 15+, Firefox 10+, Safari 6+, Edge 12+</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要方法</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">element.requestFullscreen()</code> - 请求全屏</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">document.exitFullscreen()</code> - 退出全屏</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">document.fullscreenElement</code> - 获取全屏元素</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">document.fullscreenEnabled</code> - 检查是否支持</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">事件监听</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">fullscreenchange</code> - 全屏状态改变</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">fullscreenerror</code> - 全屏请求失败</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>视频播放器全屏模式</li>
              <li>游戏和交互式应用</li>
              <li>图片和幻灯片展示</li>
              <li>在线编辑器和IDE</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">注意事项</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>必须由用户手势触发（点击、按键等）</li>
              <li>某些浏览器需要使用带前缀的API</li>
              <li>全屏时ESC键可以退出</li>
              <li>iframe中使用需要特殊权限</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, useTemplateRef } from 'vue'

// 类型定义
interface EventLog {
  event: string
  details: string
  timestamp: number
}

// 响应式状态
const isSupported = ref(false)
const isFullscreen = ref(false)
const fullscreenElement = ref('')
const showFullscreenControls = ref(true)
const preventScroll = ref(false)
const autoHideCursor = ref(false)
const editorContent = ref('# 全屏编辑器演示\n\n在这里编辑内容，点击全屏按钮体验全屏编辑模式。\n\n全屏模式下：\n- 更大的编辑空间\n- 专注的写作环境\n- 按 ESC 退出全屏')
const eventLogs = ref<EventLog[]>([])
const error = ref('')

// 模板引用
const imageContainer = useTemplateRef<HTMLDivElement>('imageContainer')
const videoContainer = useTemplateRef<HTMLDivElement>('videoContainer')
const videoElement = useTemplateRef<HTMLVideoElement>('videoElement')
const customContainer = useTemplateRef<HTMLDivElement>('customContainer')
const editorContainer = useTemplateRef<HTMLDivElement>('editorContainer')

// 初始化
onMounted(() => {
  checkSupport()
  addEventListeners()
})

// 清理
onUnmounted(() => {
  removeEventListeners()
})

// 检查浏览器支持
const checkSupport = () => {
  isSupported.value = !!(
    document.fullscreenEnabled ||
    (document as any).webkitFullscreenEnabled ||
    (document as any).mozFullScreenEnabled ||
    (document as any).msFullscreenEnabled
  )
}

// 添加事件监听器
const addEventListeners = () => {
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('mozfullscreenchange', handleFullscreenChange)
  document.addEventListener('MSFullscreenChange', handleFullscreenChange)
  
  document.addEventListener('fullscreenerror', handleFullscreenError)
  document.addEventListener('webkitfullscreenerror', handleFullscreenError)
  document.addEventListener('mozfullscreenerror', handleFullscreenError)
  document.addEventListener('MSFullscreenError', handleFullscreenError)
}

// 移除事件监听器
const removeEventListeners = () => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange)
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange)
  
  document.removeEventListener('fullscreenerror', handleFullscreenError)
  document.removeEventListener('webkitfullscreenerror', handleFullscreenError)
  document.removeEventListener('mozfullscreenerror', handleFullscreenError)
  document.removeEventListener('MSFullscreenError', handleFullscreenError)
}

// 处理全屏状态变化
const handleFullscreenChange = () => {
  const fullscreenElem = getFullscreenElement()
  isFullscreen.value = !!fullscreenElem
  
  if (fullscreenElem) {
    fullscreenElement.value = fullscreenElem.id || fullscreenElem.className || '未知元素'
    addEventLog('进入全屏', `元素进入全屏模式`)
  } else {
    fullscreenElement.value = ''
    addEventLog('退出全屏', '已退出全屏模式')
  }
}

// 处理全屏错误
const handleFullscreenError = () => {
  error.value = '无法进入全屏模式，可能是权限问题或浏览器限制'
  addEventLog('全屏错误', '请求全屏失败')
}

// 获取全屏元素
const getFullscreenElement = (): Element | null => {
  return (
    document.fullscreenElement ||
    (document as any).webkitFullscreenElement ||
    (document as any).mozFullScreenElement ||
    (document as any).msFullscreenElement ||
    null
  )
}

// 请求全屏
const requestFullscreen = async (element: HTMLElement) => {
  try {
    error.value = ''
    
    if (element.requestFullscreen) {
      await element.requestFullscreen()
    } else if ((element as any).webkitRequestFullscreen) {
      await (element as any).webkitRequestFullscreen()
    } else if ((element as any).mozRequestFullScreen) {
      await (element as any).mozRequestFullScreen()
    } else if ((element as any).msRequestFullscreen) {
      await (element as any).msRequestFullscreen()
    } else {
      throw new Error('浏览器不支持全屏API')
    }
  } catch (err) {
    console.error('请求全屏失败:', err)
    error.value = err instanceof Error ? err.message : '请求全屏失败'
  }
}

// 退出全屏
const exitFullscreen = async () => {
  try {
    if (document.exitFullscreen) {
      await document.exitFullscreen()
    } else if ((document as any).webkitExitFullscreen) {
      await (document as any).webkitExitFullscreen()
    } else if ((document as any).mozCancelFullScreen) {
      await (document as any).mozCancelFullScreen()
    } else if ((document as any).msExitFullscreen) {
      await (document as any).msExitFullscreen()
    }
  } catch (err) {
    console.error('退出全屏失败:', err)
    error.value = err instanceof Error ? err.message : '退出全屏失败'
  }
}

// 切换页面全屏
const togglePageFullscreen = async () => {
  if (isFullscreen.value) {
    await exitFullscreen()
  } else {
    await requestFullscreen(document.documentElement)
  }
}

// 切换图片全屏
const toggleImageFullscreen = async () => {
  if (!imageContainer.value) return
  
  if (isFullscreen.value && getFullscreenElement() === imageContainer.value) {
    await exitFullscreen()
  } else {
    await requestFullscreen(imageContainer.value)
  }
}

// 切换视频全屏
const toggleVideoFullscreen = async () => {
  if (!videoContainer.value) return
  
  if (isFullscreen.value && getFullscreenElement() === videoContainer.value) {
    await exitFullscreen()
  } else {
    await requestFullscreen(videoContainer.value)
  }
}

// 切换自定义内容全屏
const toggleCustomFullscreen = async () => {
  if (!customContainer.value) return
  
  if (isFullscreen.value && getFullscreenElement() === customContainer.value) {
    await exitFullscreen()
  } else {
    await requestFullscreen(customContainer.value)
  }
}

// 切换编辑器全屏
const toggleEditorFullscreen = async () => {
  if (!editorContainer.value) return
  
  if (isFullscreen.value && getFullscreenElement() === editorContainer.value) {
    await exitFullscreen()
  } else {
    await requestFullscreen(editorContainer.value)
  }
}

// 添加事件日志
const addEventLog = (event: string, details: string) => {
  eventLogs.value.push({
    event,
    details,
    timestamp: Date.now()
  })
  
  // 只保留最近20条记录
  if (eventLogs.value.length > 20) {
    eventLogs.value.splice(0, eventLogs.value.length - 20)
  }
}

// 清空事件日志
const clearEventLogs = () => {
  eventLogs.value = []
}

// 格式化时间戳
const formatTimestamp = (timestamp: number): string => {
  return new Date(timestamp).toLocaleTimeString('zh-CN')
}
</script>

<style scoped>
/* 全屏样式 */
:fullscreen,
:-webkit-full-screen,
:-moz-full-screen,
:-ms-fullscreen {
  background-color: #0a0a0a;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 全屏时的图片容器 */
#imageContainer:fullscreen,
#imageContainer:-webkit-full-screen,
#imageContainer:-moz-full-screen {
  background-color: #000;
}

#imageContainer:fullscreen img,
#imageContainer:-webkit-full-screen img,
#imageContainer:-moz-full-screen img {
  max-height: 100vh;
  max-width: 100vw;
  object-fit: contain;
}

/* 全屏时的视频容器 */
#videoContainer:fullscreen video,
#videoContainer:-webkit-full-screen video,
#videoContainer:-moz-full-screen video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 全屏时的编辑器 */
#editorContainer:fullscreen,
#editorContainer:-webkit-full-screen,
#editorContainer:-moz-full-screen {
  padding: 2rem;
}

#editorContainer:fullscreen textarea,
#editorContainer:-webkit-full-screen textarea,
#editorContainer:-moz-full-screen textarea {
  height: 100%;
  font-size: 1.125rem;
}
</style>
